import React from 'react';
import { X, Download, Share2, Eye, ExternalLink, Copy } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';

const FilePreviewDialog = ({ open, onOpenChange, file, previewUrl }) => {
  if (!file) return null;

  // 获取认证token并拼接到预览URL
  const getPreviewUrlWithToken = () => {
    if (!previewUrl) return null;
    
    const token = localStorage.getItem('authToken') || sessionStorage.getItem('authToken');
    if (!token) return previewUrl;
    
    // 检查URL是否已经包含查询参数
    const separator = previewUrl.includes('?') ? '&' : '?';
    return `${previewUrl}${separator}accessToken=${token}`;
  };

  const finalPreviewUrl = getPreviewUrlWithToken();

  // 处理下载 - 使用文件列表的 fileUrl 字段
  const handleDownload = () => {
    if (file.fileUrl) {
      // 获取认证token
      const token = localStorage.getItem('authToken') || sessionStorage.getItem('authToken');
      
      // 构建下载URL，添加token参数
      let downloadUrl = file.fileUrl;
      if (token) {
        const separator = downloadUrl.includes('?') ? '&' : '?';
        downloadUrl = `${downloadUrl}${separator}accessToken=${token}`;
      }
      
      // 创建隐藏的a标签进行下载
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = file.name; // 设置下载文件名
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      console.warn('文件下载链接不存在:', file.name);
      alert('该文件暂无下载链接');
    }
  };

  // 处理分享 - 复制 previewUrl 到剪贴板
  const handleShare = async () => {
    if (file.previewUrl) {
      try {
        await navigator.clipboard.writeText(file.previewUrl);
        alert('预览链接已复制到剪贴板');
      } catch (err) {
        console.error('复制失败:', err);
        // 降级方案：使用传统方法复制
        const textArea = document.createElement('textarea');
        textArea.value = file.previewUrl;
        document.body.appendChild(textArea);
        textArea.select();
        try {
          document.execCommand('copy');
          alert('预览链接已复制到剪贴板');
        } catch (fallbackErr) {
          console.error('降级复制也失败:', fallbackErr);
          alert('复制失败，请手动复制链接');
        }
        document.body.removeChild(textArea);
      }
    } else {
      alert('该文件暂无预览链接');
    }
  };

  // 处理新窗口打开
  const handleOpenInNewWindow = () => {
    if (finalPreviewUrl) {
      window.open(finalPreviewUrl, '_blank', 'noopener,noreferrer');
    } else {
      alert('该文件暂无预览链接');
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-4xl max-h-[90vh] overflow-hidden">
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <Eye className="w-5 h-5" />
              <span>文件预览</span>
            </div>
            <div className="flex items-center space-x-2">
              <Button variant="outline" size="sm" onClick={handleShare}>
                <Copy className="w-4 h-4 mr-2" />
                分享
              </Button>
              <Button variant="outline" size="sm" onClick={handleOpenInNewWindow}>
                <ExternalLink className="w-4 h-4 mr-2" />
                新窗口打开
              </Button>
              <Button variant="outline" size="sm" onClick={handleDownload}>
                <Download className="w-4 h-4 mr-2" />
                下载
              </Button>
            </div>
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* 文件信息 */}
          <div className="p-4 bg-material-grey-50 rounded-lg">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div>
                <span className="font-medium text-material-grey-700">文件名：</span>
                <span className="text-material-grey-600">{file.name}</span>
              </div>
              <div>
                <span className="font-medium text-material-grey-700">大小：</span>
                <span className="text-material-grey-600">{file.size}</span>
              </div>
              <div>
                <span className="font-medium text-material-grey-700">类型：</span>
                <span className="text-material-grey-600">{file.type}</span>
              </div>
              <div>
                <span className="font-medium text-material-grey-700">修改时间：</span>
                <span className="text-material-grey-600">{file.modified}</span>
              </div>
            </div>
          </div>

          {/* 预览区域 */}
          <div className="relative border border-material-grey-200 rounded-lg overflow-hidden">
            {finalPreviewUrl ? (
              <iframe
                src={finalPreviewUrl}
                className="w-full h-[60vh] border-0"
                title={`预览 ${file.name}`}
                onError={(e) => {
                  console.error('预览加载失败:', e);
                }}
              />
            ) : (
              <div className="flex items-center justify-center bg-material-grey-50 h-[60vh]">
                <div className="text-center">
                  <Eye className="w-12 h-12 text-material-grey-400 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                    无法预览此文件
                  </h3>
                  <p className="text-material-grey-500">
                    该文件类型暂不支持在线预览，请下载后查看
                  </p>
                  <Button 
                    onClick={handleDownload}
                    className="mt-4 bg-primary hover:bg-primary-600"
                  >
                    <Download className="w-4 h-4 mr-2" />
                    下载文件
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 底部按钮 */}
        <div className="flex justify-end pt-4 border-t">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            关闭
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default FilePreviewDialog;
